package com.infinit.selfhelp.common.net.interceptor

import com.drake.channel.sendEvent
import com.drake.net.exception.NetSocketTimeoutException
import com.drake.tooltip.toast
import com.infinit.selfhelp.common.event.TimeoutEvent
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeUnit

// 创建一个自定义拦截器，用于设置超时和统一处理超时异常
class TimeoutInterceptor(
    private val connectTimeout: Long,
    private val readTimeout: Long,
    private val writeTimeout: Long
) : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest: Request = chain.request()

        val newBuilder = chain.withConnectTimeout(connectTimeout.toInt(), TimeUnit.SECONDS)
            .withReadTimeout(readTimeout.toInt(), TimeUnit.SECONDS)
            .withWriteTimeout(writeTimeout.toInt(), TimeUnit.SECONDS)

        return try {
            newBuilder.proceed(originalRequest)
        } catch (e: NetSocketTimeoutException) {
            // 统一处理超时异常
            println("${e.message}")
            sendEvent(TimeoutEvent(true))
            throw e
        }
    }
}